// The payment page
// ================

define(['zepto', 'utils', 'wxshare', 'cityPicker'], function($, utils, wxshare) {
  return {

    init: function(data) {
      
      // forbidden wx share
      wxshare.initShare(data.jsConfig, false)
      
      this.bindGenderSelect();

      this.bindShapeChoose();

      this.calculateBmi();

      this.bindSubmitAction();

    },

    bindGenderSelect: function(sites) {
        
      var that = this,
          $genderSelector = $("input[name='genderSelector']")
      
      $genderSelector.picker({
        toolbarTemplate: '<header class="bar bar-nav">\
                            <button class="button button-link pull-right close-picker">确定</button>\
                            <h1 class="title">请选择性别</h1>\
                         </header>',
        cols: [
          {
            textAlign: 'center',
            values: ['MALE', 'FEMALE'],
            displayValues: ['男', '女']
          }
        ],
        formatValue: function (picker, value, displayValue){
          $(this.input).next().val(value)
          that._genderChange()
          return displayValue
        }
      });
      
    },

    _genderChange: function() {
        var gender=$('input[name="gender"]').val();
        if(gender=='MALE'){
          $('.shape-male').removeClass("hide").siblings().addClass("hide");
        }else{
          $('.shape-male').addClass("hide").siblings().removeClass("hide");
        }
        
        $('.select-shape img').each(function(e){
          $(this).removeClass("active");
        })
        $('input[name="shapeId"]').val("");
    },

    bindShapeChoose: function(){
      //取旧的src
      $('.select-shape').on('click','img',function(){
        $('.select-shape img').each(function(){
          $(this).removeClass("active");
        });
        //选中的更新
        $(this).addClass("active");
        $('.select-shape').children('input[name="shapeId"]').val($(this).data('shape'));
      });
    },
    
    calculateBmi: function() {
      var that = this;
      $(document).on("change", "input[name='height'], input[name='weight']", function(e){
        
        //Obtain user inputs
        var height=Number($("input[name='height']").val());
        var weight=Number($("input[name='weight']").val());
        
        if(height && weight) {
          //Perform calculation
          var BMI=weight/Math.pow((height / 100),2);
          $("input[name='bmiValue']").val(BMI.toFixed(2))
        }
      })

    },

    // order submit evvent handler
    bindSubmitAction: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.button-submit")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          // do submit order with data
          data = thatSubmit.onAppendData(data)
          thatSubmit.onSubmitOrder(data)
        }
      })
      
    },

    // init data
    onInitData: function() {
      return {
        '_method': {
          'value': $('input[name="_method"]').val().trim(),
          'message': '提交方式不能为空'
        },
        'height': {
          'value': $('input[name="height"]').val().trim(),
          'message': '身高不能为空'
        },
        'weight': {
          'value': $('input[name="weight"]').val().trim(),
          'message': '请填写体重'
        },
        'age': {
          'value': $('input[name="age"]').val().trim(),
          'message': '请填写年龄'
        },
        'gender': {
          'value': $('input[name="gender"]').val().trim(),   
          'message': '性别不能为空'
        },
        'shapeId': {
          'value': $('input[name="shapeId"]').val().trim(),   
          'message': '体型不能为空'
        }
      }
    },
    
    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)

      var height = data.height.value;
      var regp = new RegExp("^[0-9]*$");
      if(!regp.test(height)) {
        $.toast("请输入正确的身高，精确到cm", 3000);
        return false;
      }

      var weight = data.weight.value;
      var regw =  /^\+?(\d*)$/;
      if(!regw.test(weight)) {
        $.toast("请输入正确的体重(kg)", 3000);
        return false;
      }

      return true
    },

    onAppendData: function(data) {
      return data;
    },

    onSubmitOrder: function(data) {

      $.showPreloader('正在提交')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/investigations/fit',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('填写身体数据成功')
            setTimeout(function() {
              window.location.href = __CTX__.root + '/investigations'
            }, 1000)
        }, function(result) {
          $.toast(result.message || '填写身体数据失败')
        })
      })
      
    }
  }
})